import datetime

from PIL.Image import Image
from django.shortcuts import render, get_object_or_404, redirect
from django.conf import settings
from django.http import HttpResponse

from removebg import RemoveBg
import os
import json

img_type = [".png", ".jpg", ".jpeg", ".gif", ".bmp"]


def rm_img_bg(pic_path):
    print(pic_path)
    rm_bg = RemoveBg("c26W5C1wGCy21JGewQRmsiTy", "error.log")
    # 引号内是你获取的API，需要自己去注册https://www.remove.bg/
    rm_bg.remove_background_from_img_file(pic_path)
    # 会自动生成一张去除背景的照片“原照片名.jpg_no_bg.png”
    return pic_path


def resumes(request, name):
    context = {
        "name": name,
    }
    # 路径是相对于manage.py的

    with open(f"./static/resume/data/{name}.json", "r", encoding="UTF-8") as load_f:
        print(name)
        try:
            load_dict = json.load(load_f)
        except Exception as e:
            print(e)
        try:
            # print(str(load_dict))
            context = dict(context, **load_dict)
            car_id = context["certificate_id"]
            ans_age = GetInformation(car_id).get_age()
            ans_gender = GetInformation(car_id).get_sex()
            context.update({"age": ans_age})
            context.update({"gender": ans_gender})
            if context["pic_url"] == "":
                user_name = context["user"]
                for ext in img_type:
                    user_img = "".join([user_name, ext, "_no_bg.png"])
                    if os.path.exists(f"./static/uploads/{user_img}"):
                        context["pic_url"] = f"/static/uploads/{user_img}"
        except Exception as e:
            print(e)
    return render(request, "blog/resume.html", context)


def upload_img(request):
    # 获取上传的图片信息
    img = request.FILES.get('person_img')
    user_name = request.POST.get('user')
    # 获取上传图片的名称
    img_name = img.name

    # 获取后缀
    ext = os.path.splitext(img_name)[1]
    if ext not in img_type:
        return HttpResponse("")
    # 重新规定图片名称，图片类型
    img_name = f'{user_name}{ext}'
    # 图片保存路径
    img_path = os.path.join(settings.IMG_UPLOAD, img_name)

    if os.path.exists(img_path):
        os.remove(img_path)

    # 写入 上传图片的 内容
    with open(img_path, 'ab') as fp:
        # 如果上传的图片非常大， 那么通过 img对象的 chunks() 方法 分割成多个片段来上传
        for chunk in img.chunks():
            fp.write(chunk)
    try:
        ans = rm_img_bg(img_path)
    except Exception as e:
        print(e)
    # AxfUser.objects.create_user(
    #     username=username,
    #     password=password,
    #     avatar=f'/static/uploads/{filename}', # 数据库 图片字段 存储路径
    #     mobile=mobile
    # )
    return HttpResponse(img_name + "_no_bg.png")


def get_img():
    pass


class GetInformation(object):

    def __init__(self, id):
        self.id = id
        self.birth_year = int(self.id[6:10])
        self.birth_month = int(self.id[10:12])
        self.birth_day = int(self.id[12:14])

    def get_birthday(self):
        """通过身份证号获取出生日期"""
        birthday = "{0}-{1}-{2}".format(self.birth_year, self.birth_month, self.birth_day)
        return birthday

    def get_sex(self):
        """男生：1 女生：2"""
        num = int(self.id[16:17])
        if num % 2 == 0:
            return "女"
        else:
            return "男"

    def get_age(self):
        """通过身份证号获取年龄"""
        now = (datetime.datetime.now() + datetime.timedelta(days=1))
        year = now.year
        month = now.month
        day = now.day

        if year == self.birth_year:
            return 0
        else:
            if self.birth_month > month or (self.birth_month == month and self.birth_day > day):
                return year - self.birth_year - 1
            else:
                return year - self.birth_year
